from django.shortcuts import render
from web.models import Project, Bug
from web.forms.search import SearchForm
from django.db.models import Q


def search(request):
    form = SearchForm(request.GET or None)
    results = {
        'projects': [],
        'bugs': [],
        'tasks': []
    }

    if form.is_valid():
        query = form.cleaned_data['search_query']
        search_type = form.cleaned_data['search_type']

        # 根据搜索类型执行不同的搜索
        if search_type == 'all' or search_type == 'project':
            results['projects'] = Project.objects.filter(
                Q(name__icontains=query) | Q(description__icontains=query)
            ).filter(participants=request.user)

        if search_type == 'all' or search_type == 'bug':
            results['bugs'] = Bug.objects.filter(
                Q(title__icontains=query) | Q(description__icontains=query)
            ).filter(project__participants=request.user)

        # 这里假设Task模型存在，根据实际情况调整
        # if search_type == 'all' or search_type == 'task':
        #     results['tasks'] = Task.objects.filter(
        #         Q(title__icontains=query) | Q(description__icontains=query)
        #     ).filter(project__participants=request.user)

    context = {
        'form': form,
        'results': results
    }
    return render(request, 'search_results.html', context)